{% extends "base.html" %}

{% block title %}基金买入点{% endblock %}

{% block extra_css %}
    <style>
        .container {
            width: 90%;
            margin: 20px auto;
        }
        .metrics {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #eee;
            border-radius: 8px;
        }
        .metrics span {
            margin-right: 30px;
            font-size: 14px;
            color: #333;
        }
        .chart-container {
            width: 100%;
            height: 600px;
            border: 1px solid #eee;
            border-radius: 8px;
            margin-bottom: 30px;
        }
        .chart-title {
            text-align: center;
            font-size: 18px;
            font-weight: bold;
            margin: 10px 0;
        }
    </style>
{% endblock %}

{% block content %}
    <div class="container">
        <div class="chart-title">MA策略图表</div>
        <div class="metrics" id="maStrategyMetrics"></div>
        <div id="maChart" class="chart-container"></div>
        <div class="chart-title">Drop策略图表</div>
        <div class="metrics" id="dropStrategyMetrics"></div>
        <div id="dropChart" class="chart-container"></div>
    </div>
{% endblock %}

{% block extra_js %}
    <script src="{{ url_for('static', filename='js/echarts.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jquery.min.js') }}"></script>
    <script type="text/javascript">
        console.log("jQuery是否加载成功：", typeof $ !== "undefined");
        console.log("ECharts是否加载成功：", typeof echarts !== "undefined");

        const fundCode = "{{ fund_code }}";
        const maRange = "{{ ma_range }}";
        const maChart = echarts.init(document.getElementById('maChart'));
        const dropChart = echarts.init(document.getElementById('dropChart'));

        // Load MA strategy data
        $.ajax({
            url: `/api/fund/visual/${fundCode}?strategy=ma&ma_range=${maRange}`,
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (!response.success) {
                    alert(`MA策略数据加载失败：${response.error}`);
                    return;
                }

                renderChart(maChart, response.data, 'MA策略');
                renderStrategyMetrics(response.data.metrics, 'ma');
            },
            error: function(xhr, status, error) {
                alert(`MA策略请求失败：${error}`);
                console.error("AJAX错误：", status, error);
                console.error("后端返回：", xhr.responseText);
            }
        });

        // Load Drop strategy data
        $.ajax({
            url: `/api/fund/visual/${fundCode}?strategy=drop`,
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                if (!response.success) {
                    alert(`Drop策略数据加载失败：${response.error}`);
                    return;
                }
                renderChart(dropChart, response.data, 'Drop策略');
                renderStrategyMetrics(response.data.metrics, 'drop');

                renderChart(dropChart, response.data, 'Drop策略');
            },
            error: function(xhr, status, error) {
                alert(`Drop策略请求失败：${error}`);
                console.error("AJAX错误：", status, error);
                console.error("后端返回：", xhr.responseText);
            }
        });

        function renderChart(chart, data, strategyName) {
            const netTrend = data.net_trend;
            const buyPoints = data.buy_points;

            // 构建精准散点数据（之前的修复逻辑保留）
            const scatterData = [];
            const invalidBuyDates = [];
            for (let i = 0; i < buyPoints.dates.length; i++) {
                const buyDate = buyPoints.dates[i];
                const buyPrice = buyPoints.prices[i];
                const xIndex = netTrend.dates.indexOf(buyDate);
                if (xIndex !== -1) {
                    scatterData.push([xIndex, buyPrice]);
                } else {
                    invalidBuyDates.push(buyDate);
                }
            }
            if (invalidBuyDates.length > 0) {
                console.warn("忽略无效买入日期：", invalidBuyDates);
            }

            const option = {
                title: {
                    text: `基金${fundCode} - ${strategyName}`,
                    left: 'center',
                    textStyle: { fontSize: 16 }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { type: 'line' },
                    formatter: function(params) {
                        let tooltipHtml = "";
                        params.forEach(param => {
                            const date = netTrend.dates[param.dataIndex];
                            if (param.seriesName === '单位净值') {
                                tooltipHtml += `<div>日期：${date}</div>`;
                                tooltipHtml += `<div>${param.seriesName}：${param.value.toFixed(4)}</div>`;
                            } else if (param.seriesName === '买入点') {
                                const buyAmount = buyPoints.costs[param.dataIndex];
                                tooltipHtml += `<div style="color:red">${param.seriesName}：${param.value[1].toFixed(4)}（投入${buyAmount}元）</div>`;
                            }
                        });
                        return tooltipHtml;
                    }
                },
                legend: {
                    data: ['单位净值', '买入点'],
                    top: 30,
                    left: 'center'
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: netTrend.dates,
                    axisLabel: {
                        rotate: 45,
                        interval: Math.ceil(netTrend.dates.length / 20)
                    },
                    splitLine: { show: false }
                },
                yAxis: {
                    type: 'value',
                    name: '单位净值',
                    min: Math.min(...netTrend.net_values) * 0.95,
                    max: Math.max(...netTrend.net_values) * 1.05,
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                series: [
                    {
                        name: '单位净值',
                        type: 'line',
                        data: netTrend.net_values,
                        smooth: true,
                        lineStyle: { color: '#4895ef', width: 2 },
                        symbol: 'none'
                    },
                    {
                        name: '买入点',
                        type: 'scatter',
                        data: scatterData,
                        symbol: 'circle',
                        symbolSize: 12,
                        itemStyle: { color: '#e74c3c' },
                        emphasis: {
                            itemStyle: { color: '#c0392b', borderWidth: 2 }
                        }
                    }
                ]
            };

            chart.setOption(option);
        }

        window.addEventListener('resize', function() {
            maChart.resize();
            dropChart.resize();
        });

        function renderStrategyMetrics(metrics, strategyType) {
            let metricsEl;
            if (strategyType === 'ma') {
                metricsEl = document.getElementById('maStrategyMetrics');
            } else if (strategyType === 'drop') {
                metricsEl = document.getElementById('dropStrategyMetrics');
            } else {
                metricsEl = document.getElementById('strategyMetrics');
            }
            
            if (metricsEl && metrics) {
                metricsEl.innerHTML = `
                    <span>总收益率：${metrics.total_return_rate}%</span>
                    <span>买入次数：${metrics.buy_times}次</span>
                `;
            }
        }
    </script>
{% endblock %}